package com.v2future.sjt.collegecheckingattendance.event;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.event.adapter.ReleaseEventImgGridAdapter;
import com.v2future.sjt.collegecheckingattendance.event.bean.OneEventTypeBean;
import com.v2future.sjt.collegecheckingattendance.event.bean.ReleaseEventImageBean;
import com.v2future.sjt.collegecheckingattendance.home.HomeActivity;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.DateUtil;
import com.v2future.sjt.collegecheckingattendance.utils.IntentKey;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.DateTimePickDialogUtil;

import org.xutils.HttpManager;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by Administrator on 2016/1/18.
 * 发布活动
 */
public class ReleaseEventActivity extends MainActivity implements View.OnClickListener{

    GridView releaseEventImageGv;

    Button releaseBtn;

    EditText releaseTitleEt,releaseContentEt;

    /**
     * 活动时间
     */
    EditText eventTimeEt;

    /**
     * 主办方
     */
    EditText eventSponorEt;

    /**
     * 活动地点
     */
    EditText eventAddrEt;

    ReleaseEventImgGridAdapter adapter;

    List<ReleaseEventImageBean> dataList;

    int REQUEST_IMAGE = 1001;

    private OneEventTypeBean selectEventType;

    @Override
    public void init() {
        imageUrls = new ArrayList<>();
        dataList = new ArrayList<>();
        selectEventType = (OneEventTypeBean) getIntent().getSerializableExtra(IntentKey.EVENT_TYPE);
        ReleaseEventImageBean addPhotoBean = new ReleaseEventImageBean();
        dataList.add(addPhotoBean);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_release_event);
        setTitleText(R.string.event_release);
        initTitleBack(null);
        releaseEventImageGv = (GridView) findViewById(R.id.gv_release_images);
        releaseEventImageGv.setOnItemClickListener(imageClickListener);
        releaseBtn = (Button) findViewById(R.id.btn_release);
        releaseBtn.setOnClickListener(this);
        releaseTitleEt = (EditText) findViewById(R.id.et_release_title);
        releaseContentEt = (EditText) findViewById(R.id.et_release_content);
        eventTimeEt = (EditText) findViewById(R.id.et_event_time);
        eventTimeEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        ReleaseEventActivity.this, null);
                dateTimePicKDialog.dateTimePicKDialog(eventTimeEt);
            }
        });
        eventSponorEt = (EditText) findViewById(R.id.et_sponsor);
        eventAddrEt = (EditText) findViewById(R.id.et_addr);
    }

    @Override
    public void initAfter() {
        adapter = new ReleaseEventImgGridAdapter(this, dataList);
        releaseEventImageGv.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                // Get the result list of select image paths
                ArrayList<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (path.size() > 0 ) {
                    imageUrls = path;//保存已选的图片路径
                    refreshImages(path);
                    showLoadingDialog();
                    new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            compressImages();
                            cancelLoadingDialog();
                        }
                    }.start();
                }
            }
        }
    }

    /**
     * 刷新图片选择显示
     * @param path
     */
    private void refreshImages(ArrayList<String> path){
        dataList.clear();
        ReleaseEventImageBean bean = null;
        for (int i=0;i<path.size();i++) {
            bean = new ReleaseEventImageBean();
            bean.setImageUrl(path.get(i).toString());
            dataList.add(bean);
        }
        bean = new ReleaseEventImageBean();
        dataList.add(bean);
        adapter.notifyDataSetChanged();
    }

    /**
     * 发布活动
     */
    private void release(){
        String title = releaseTitleEt.getText().toString();
        String content = releaseContentEt.getText().toString();
        String dateTime = eventTimeEt.getText().toString();
        String sponsor = eventSponorEt.getText().toString();
        String addr = eventAddrEt.getText().toString();
        if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content) ||
                TextUtils.isEmpty(dateTime) || TextUtils.isEmpty(sponsor) ||
                TextUtils.isEmpty(addr)) {
            tip("请完整活动相关信息");
            return;
        }
        BaseRequestParams params = new BaseRequestParams(ReleaseEventActivity.this, formatUrlDo(Constants.PUBLISH_EVENT));
        params.setMultipart(true);
        params.addQueryStringParameter("actionTime", dateTime);
        params.addQueryStringParameter("actionTitle", title);
        params.addQueryStringParameter("actionArea", addr);
        params.addQueryStringParameter("sponsor", sponsor);
        params.addQueryStringParameter("subjectId", selectEventType.getSubjectId());
        params.addQueryStringParameter("userCode", getUserInfo().getData().getUserCode());
        params.addQueryStringParameter("actionDesc", content);
        final Bitmap bitmap;
        if (null != imageUrls && imageUrls.size() > 0) {
            for (int i=0;i<imageUrls.size();i++) {
                params.addQueryStringParameter("imageName"+i, urlEncode(imageUrls.get(i).toString()));
//                params.addBodyParameter("imageBody"+i, new File(imageUrls.get(i).toString()), null);
                params.addBodyParameter("imageBody"+i, imageFiles.get(i), null);
            }
        }
        showLoadingDialog();
        NetUtils.doPostRequestWithFiles(this, params, new NetTaskListener<BaseResponseBean>() {

            @Override
            public void onSuccess(BaseResponseBean result) {
                showOneBtnDialog("提示", "上传活动成功", "知道了", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ReleaseEventActivity.this, HomeActivity.class);
                        intent.putExtra("id", HomeActivity.FLAG_EVENT);
                        intent.putExtra(HomeActivity.INTENT_TAG_REFRESH, true);
                        gobackWithData(intent);
                    }
                });
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    AdapterView.OnItemClickListener imageClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            if (dataList.get(position).getImageUrl() == null) {
                Intent intent = new Intent(ReleaseEventActivity.this, MultiImageSelectorActivity.class);
                // whether show camera
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
                // max select image amount
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 4);
                // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                // default select images (support array list)
                intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, imageUrls);
                startActivityForResult(intent, REQUEST_IMAGE);
//            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_release:
                release();
                break;
            default:
                break;
        }
    }
}
